#include "uidemo3.h"
#include "ui_uidemo3.h"
#include "quiwidget.h"
#include "frmdevice.h"
#include "qtimer.h"
#include "tablewidget.h"
static QString con;
static int num = 0;
static int field_num = 0;
static int record_num = 0;
#define TEST 1
#if TEST
#define URL_DEFINE_CREATE "http://mock.apifox.cn/m1/1838418-0-default/define/create"
#define URL_DEFINE_ALTER "http://mock.apifox.cn/m1/1838418-0-default/define/alter"
#define URL_DEFINE_DEL "http://mock.apifox.cn/m1/1838418-0-default/define/drop"
#define URL_DEFINE_DETAIL "http://mock.apifox.cn/m1/1838418-0-default/define/detail"
#define URL_DEFINE_LIST "http://mock.apifox.cn/m1/1838418-0-default/define/list"
#define URL_DEFINE_CREATE_RELATION "https://mock.apifox.cn/m1/1838418-0-default/define/saveRelation"
#define URL_DEFINE_ASK_RELATION "https://mock.apifox.cn/m1/1838418-0-default/define/askRelation"
#define URL_DEFINE_DEL_RELATION "https://mock.apifox.cn/m1/1838418-0-default/define/delRelation"
#define URL_DEFINE_ASK_ALLRELATION "https://mock.apifox.cn/m1/1838418-0-default/define/askAllRelation"
//xym
#define URL_COLLECTION_GETFORMDATA "https://mock.apifox.cn/m1/1838418-0-default/collection/getFormData"
#define URL_COLLECTION_DELETEFORM "https://mock.apifox.cn/m1/1838418-0-default/collection/deleteForm"
#define URL_COLLECTION_GETFORMINFO "http://mock.apifox.cn/m1/1838418-0-default/collection/getFormInfo"
#define URL_COLLECTION_GETFORMLIST "http://124.70.0.60/collection/getFormList"
//lkl
#define URL_ANALYSE_DETAIL "http://mock.apifox.cn/m1/1838418-0-default/analyse/detail"
#define URL_ANALYSE_FILTRATE "https://mock.apifox.cn/m1/1838418-0-default/analyse/filtrate"
#define URL_ANALYSE_SORT "https://mock.apifox.cn/m1/1838418-0-default/analyse/sort"
#define URL_ANALYSE_RECORD "https://mock.apifox.cn/m1/1838418-0-default/analyse/record"
//lkl
#else
#define URL_DEFINE_CREATE "http://124.70.0.60/define/create"
#define URL_DEFINE_ALTER "http://124.70.0.60/define/alter"
#define URL_DEFINE_DEL "http://124.70.0.60/define/drop"
#define URL_DEFINE_DETAIL "http://124.70.0.60/define/detail"
#define URL_DEFINE_LIST "http://124.70.0.60/define/list"
#define URL_DEFINE_CREATE_RELATION "http://124.70.0.60/define/saveRelation"
#define URL_DEFINE_ASK_RELATION "http://124.70.0.60/define/askRelation"
#define URL_DEFINE_DEL_RELATION "http://124.70.0.60/define/delRelation"
#define URL_DEFINE_ASK_ALLRELATION "http://124.70.0.60/define/askAllRelation"
//lkl
#define URL_ANALYSE_DETAIL "http://124.70.0.60/analyse/detail"
#define URL_ANALYSE_FILTRATE "http://124.70.0.60/analyse/filtrate"
#define URL_ANALYSE_SORT "http://124.70.0.60/analyse/sort"
#define URL_ANALYSE_RECORD "http://124.70.0.60/analyse/record"
//xym
#define URL_COLLECTION_GETFORMDATA "http://124.70.0.60/collection/getFormData"
#define URL_COLLECTION_DELETEFORM "http://124.70.0.60/collection/deleteForm"
#define URL_COLLECTION_GETFORMINFO "http://124.70.0.60/collection/getFormInfo"
#define URL_COLLECTION_GETFORMLIST "http://124.70.0.60/collection/getFormList"
#endif




UIDemo3::UIDemo3(QWidget *parent) : QDialog(parent),
    ui(new Ui::UIDemo3)
{
    ui->setupUi(this);
    this->initForm();
    this->initTreeWidget();
    this->initTableWidget();
    this->initMenu();
    this->setGeometry(0, 0, 900, 600);
    this->inittableview();
    ui->stackedWidget->setCurrentIndex(0);
    QUIWidget::setFormInCenter(this);
    QTimer::singleShot(100, this, SLOT(initPanelWidget()));
    manager = new QNetworkAccessManager(this);
    timerLineRefresh=new QTimer;
    // 定时器，每秒钟更新一次直线的位置
    timerLineRefresh->start(10); // 每秒钟更新一次直线的位置
    QObject::connect(timerLineRefresh,SIGNAL(timeout()),this,SLOT(updateLine()));
}


void UIDemo3::inittableview(){
    ui->refreshTableViewButton->setEnabled(false);
    // 构造scene和view
    tablescene=new QGraphicsScene;
    QPixmap bgPixmap(":/images/title_bk2.jpg");
    QBrush bgBrush(bgPixmap);
    tablescene->setBackgroundBrush(bgBrush);
    tableview = new QGraphicsView(tablescene);
    tablewidget0 = new QWidget;
    tablelayout=new QVBoxLayout(tablewidget0);
    tablelayout->addWidget(tableview);
    ui->frameTableView->setLayout(tablelayout);
    // 调整场景的大小和视图的显示
    tableview->fitInView(tablescene->sceneRect(), Qt::KeepAspectRatio);
    tableview->setRenderHint(QPainter::Antialiasing);
    tableview->setDragMode(QGraphicsView::ScrollHandDrag);
    tableview->setCacheMode(QGraphicsView::CacheBackground);
    tableview->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
    tableview->show();
    tableview->setHidden(true);
}


void UIDemo3::tableshow(){
    qDebug()<<relationRecord;
    timerLineRefresh->stop();
    table2proxy.clear();
    tableview->setHidden(false);
    tablescene->clear();
    linerelation.clear();
    timerLineRefresh->start();
    QIcon primary(":/images/primary.png");
    QIcon allownull(":/images/allownull.png");
    QIcon unique(":/images/unique.png");
    int i=0;
    int num=int(round(sqrt(fieldRecord.size())));
    for(auto tablename:fieldRecord.keys()){
        //为每个表构造相应的proxywidget
        tablewidget *t1=new tablewidget();
        t1->addItem(tablename);
        t1->item(0)->setTextColor("red");
        t1->item(0)->setFont(QFont("Arial", 12, QFont::Bold));
        QFont font = t1->item(0)->font();
        font.setUnderline(true);
        t1->item(0)->setFont(font);
        for(auto attrname:fieldRecord[tablename].keys()){
            QString stritem="-   "+attrname+"   ("+fieldRecord[tablename][attrname]["type"].toString()+")";
            t1->addItem(stritem);
            if(fieldRecord[tablename][attrname]["primary"].toBool()==true){
                t1->item(t1->model()->rowCount()-1)->setIcon(primary);
            }
            //            if(fieldRecord[tablename][attrname]["allownull"].toBool()==true){
            //                t1->item(t1->model()->rowCount()-1)->setIcon(allownull);
            //            }
            //            if(fieldRecord[tablename][attrname]["unique"].toBool()==true){
            //                t1->item(t1->model()->rowCount()-1)->setIcon(unique);
            //            }
        }
        QGraphicsProxyWidget *proxy1=tablescene->addWidget(t1);
        table2proxy.insert(tablename,proxy1);
        proxy1->setPos(i%num*140*1.5,i/num*180*1.5);
        proxy1->setGeometry(QRectF(i%num*140*1.8,i/num*180*1.8,140,180));
        proxy1->setZValue(1);
        i++;
    }
    // 连接所有关系
    for(auto pattern1:relationRecord.keys()){
        QGraphicsProxyWidget *proxy1=table2proxy[pattern1];
        for(auto pattern2:relationRecord[pattern1].keys()){
            QGraphicsProxyWidget *proxy2=table2proxy[pattern2];
            // 创建一条连接两个控件中心的直线
            // 计算两个QListWidget控件的中心位置
            QPointF center1 = proxy1->mapToScene(proxy1->boundingRect().center());
            QPointF center2 = proxy2->mapToScene(proxy2->boundingRect().center());
            QGraphicsLineItem *line = new QGraphicsLineItem();
            QPen pen(Qt::red, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
            line->setPen(QPen(Qt::yellow, 2));
            tablescene->addItem(line);
            line->setLine(center1.x(), center1.y(), center2.x(), center2.y());
            line->setZValue(0);
            // 构造一个文本项
            QString rname=relationRecord[pattern1][pattern2].first;
            QString rtype=relationRecord[pattern1][pattern2].second;
            QGraphicsTextItem *nametext = new QGraphicsTextItem(rname);
            QGraphicsTextItem *type1text = new QGraphicsTextItem(rtype.mid(0,1));
            QGraphicsTextItem *type2text = new QGraphicsTextItem(rtype.mid(2,1));
            // 设置线为文本的父项
            nametext->setParentItem(line);
            type1text->setParentItem(line);
            type2text->setParentItem(line);
            // 设置文本的z值大于线的z值,以显示在线的上层
            nametext->setZValue(1);
            type1text->setZValue(1);
            type2text->setZValue(1);
            type1text->setDefaultTextColor(QColor(0, 0, 255));
            type2text->setDefaultTextColor(QColor(0, 0, 255));
            // 放入vector，方便更新
            lineRelation *l=new lineRelation(line,nametext,type1text,type2text,proxy1,proxy2);
            linerelation.push_back(l);
        }
    }
}

void UIDemo3::updateLine(){
    for(auto line:linerelation){
        line->update();
    }
}

void UIDemo3::on_refreshTableViewButton_clicked(){
    tableshow();
}
void UIDemo3::on_comboBox_otherTable_currentIndexChanged(int){
    if(ui->comboBox_otherTable->currentText()=="请选择"){
        ui->comboBox_relation->setCurrentText("请选择类型");
        ui->delRelationButton->setEnabled(false);
        ui->relationLine->setText("");
        return;
    }
    //查询当前的表的所有的表关系
    QString user("test");
    QString token("test");
    QString md5("test");
    QJsonObject relation;
    relation.insert("pattern1",ui->tableNameLineEdit->text());
    relation.insert("pattern2",ui->comboBox_otherTable->currentText());
    QJsonObject postObject;
    postObject.insert("user", user);
    postObject.insert("token", token);
    postObject.insert("md5", md5);
    postObject.insert("relation", relation);
    // 转换为bytearray，可以进行post
    QJsonDocument postDocument;
    postDocument.setObject(postObject);
    QByteArray postData = postDocument.toJson(QJsonDocument::Compact);
    // 打印post数据
    qDebug() << postObject;
    // 发送请求,查询表的属性
    QNetworkRequest request;
    request.setUrl(QUrl(URL_DEFINE_ASK_RELATION));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    QNetworkReply *reply = manager->post(request, postData);
    connect(reply, &QNetworkReply::finished, [=]()
    {
        QJsonDocument replyJson = parseReply(reply);
        QJsonObject obj=replyJson.object();
        if(obj["code"]=="100"){
            QJsonValue v=obj.value("relation");
            QJsonObject relation=v.toObject();
            if(relation["type"].toString()=="1-1"){
                ui->comboBox_relation->setCurrentText("一对一");
            }
            else if(relation["type"].toString()=="1-n"){
                ui->comboBox_relation->setCurrentText("一对多");
            }
            else if(relation["type"].toString()=="n-1"){
                ui->comboBox_relation->setCurrentText("多对一");
            }
            else if(relation["type"].toString()=="n-n"){
                ui->comboBox_relation->setCurrentText("多对多");
            }
            else{
                ui->comboBox_relation->setCurrentText("请选择类型");
                ui->delRelationButton->setEnabled(false);
                ui->relationLine->setText("");
                return;
            }
            ui->delRelationButton->setEnabled(true);
            ui->relationLine->setText(relation["name"].toString());
        }
        else{
            ui->comboBox_relation->setCurrentText("请选择类型");
            ui->delRelationButton->setEnabled(false);
            ui->relationLine->setText("");
        }

    });
}


void UIDemo3::on_delRelationButton_clicked(){
    QString user("test");
    QString token("test");
    QString md5("test");
    QJsonObject relation;
    relation.insert("pattern1",ui->tableNameLineEdit->text());
    relation.insert("pattern2",ui->comboBox_otherTable->currentText());
    QJsonObject postObject;
    postObject.insert("user", user);
    postObject.insert("token", token);
    postObject.insert("md5", md5);
    postObject.insert("relation", relation);
    // 转换为bytearray，可以进行post
    QJsonDocument postDocument;
    postDocument.setObject(postObject);
    QByteArray postData = postDocument.toJson(QJsonDocument::Compact);
    // 打印post数据
    qDebug() << postObject;
    // 发送请求,查询表的属性
    QNetworkRequest request;
    request.setUrl(QUrl(URL_DEFINE_DEL_RELATION));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    QNetworkReply *reply = manager->post(request, postData);
    connect(reply, &QNetworkReply::finished, [=]()
    {
        QJsonDocument replyJson = parseReply(reply);
        QJsonObject obj=replyJson.object();
        if(obj["code"]=="100"){
            QMessageBox::information(this,  "数据模式关系","删除成功");
        }
        else{
            QMessageBox::critical(this,  "数据模式关系","删除失败");
        }
    });

}

void UIDemo3::on_refreshTableButton_clicked(){
    on_btnDefine_clicked();
}
void UIDemo3::on_amplifyButton_clicked(){
    tableview->scale(1.2,1.2);

}
void UIDemo3::on_reduceButton_clicked(){
    tableview->scale(0.8,0.8);
}

UIDemo3::~UIDemo3()
{
    delete ui;
}

void UIDemo3::initForm()
{

    ui->splitter_y100->setSizes({10,300});
    this->max = false;
    this->location = this->geometry();
    this->setProperty("form", true);
    this->setProperty("canMove", true);
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint);

    IconHelper::Instance()->setIcon(ui->labIco, QChar(0xF099), 30);
    IconHelper::Instance()->setIcon(ui->btnMenu_Min, QChar(0xF068));
    IconHelper::Instance()->setIcon(ui->btnMenu_Max, QChar(0xF067));
    IconHelper::Instance()->setIcon(ui->btnMenu_Close, QChar(0xF00d));

    ui->widgetTitle->setProperty("form", "title");
    ui->widgetTop->setProperty("nav", "top");
    ui->labTitle->setText("数据管理平台");
    ui->labTitle->setFont(QFont("Microsoft Yahei", 20));
    this->setWindowTitle(ui->labTitle->text());

    QSize icoSize(32, 32);
    int icoWidth = 85;

    // 设置顶部导航按钮
    QList<QToolButton *> tbtns = ui->widgetTop->findChildren<QToolButton *>();
    foreach (QToolButton *btn, tbtns)
    {
        btn->setIconSize(icoSize);
        btn->setMinimumWidth(icoWidth);
    }

    QList<int> widths;
    widths << 170 << 650;
    ui->splitter_x->setSizes(widths);

    QList<int> heights;
    heights << 300 << 2000 << 300;
    ui->splitter_y->setSizes(heights);
}

void UIDemo3::initTreeWidget()
{
    QTreeWidgetItemIterator it(ui->treeWidget);
    QObject::connect(ui->treeWidget, &QTreeWidget::itemClicked, [=](QTreeWidgetItem *, int)
    {
        int row=ui->treeWidget->currentIndex().row();
        ui->stackedWidget_define->setCurrentIndex(row);
        // 查看模式，需要获取所有的表及他们的信息
        if(row==1){
            ui->refreshTableViewButton->setEnabled(false);
            ui->amplifyButton->setEnabled(false);
            ui->reduceButton->setEnabled(false);
            QTimer::singleShot(2000,[=](){
                ui->refreshTableViewButton->setEnabled(true);
                ui->amplifyButton->setEnabled(true);
                ui->reduceButton->setEnabled(true);
            });
            timerLineRefresh->stop();
            fieldRecord.clear();
            relationRecord.clear();
            table2proxy.clear();
            tableview->setHidden(false);
            tablescene->clear();
            linerelation.clear();
            timerLineRefresh->start();
            // 查询所有表
            QString user("test");
            QString token("test");
            QString md5("test");
            // 构造post数据
            QJsonObject json;
            json.insert("user", user);
            json.insert("token", token);
            json.insert("md5", md5);
            QJsonDocument document;
            document.setObject(json);
            QByteArray dataArray = document.toJson(QJsonDocument::Compact);
            // 发送post数据
            QByteArray postData = document.toJson(QJsonDocument::Compact);
            // 打印post数据
            qDebug() << json;
            // 发送post请求
            QNetworkRequest request;
            request.setUrl(QUrl(URL_DEFINE_LIST));
            request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
            QNetworkReply *reply = manager->post(request, postData);
            connect(reply, &QNetworkReply::finished, [=]()
            {
                QJsonDocument replyJson = parseReply(reply);
                //解析返回数据
                QJsonObject obj = replyJson.object();
                // 判断连接是否正常
                if(obj["code"]=="100"){
                    QJsonArray arr=obj["tables"].toArray();
                    for (int i = 0; i < arr.count(); i++){
                        QString tablename=arr[i].toString();
                        // 构造post数据
                        QString user("test");
                        QString token("test");
                        QString md5("test");
                        QJsonObject tableObject;
                        tableObject.insert("name", tablename);
                        QJsonObject postObject;
                        postObject.insert("user", user);
                        postObject.insert("token", token);
                        postObject.insert("md5", md5);
                        postObject.insert("table", tableObject);
                        // 转换为bytearray，可以进行post
                        QJsonDocument postDocument;
                        postDocument.setObject(postObject);
                        QByteArray postData = postDocument.toJson(QJsonDocument::Compact);
                        // 打印post数据
                        qDebug() << postObject;
                        // 发送请求,查询表的属性
                        QNetworkRequest request;
                        request.setUrl(QUrl(URL_DEFINE_DETAIL));
                        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
                        QNetworkReply *reply = manager->post(request, postData);
                        connect(reply, &QNetworkReply::finished, [=]()
                        {
                            QMap<QString,QMap<QString,QMap<QString,QVariant>>> &f=fieldRecord;
                            // 解析返回的数据并获取对象
                            QJsonDocument replyJson = parseReply(reply);
                            QJsonObject obj = replyJson.object();
                            // 判断连接是否正常
                            if(obj["code"]=="100"){
                                QJsonValue userValue=obj.value("table");
                                QJsonObject userObj = userValue.toObject();
                                QJsonArray arr1=userObj["field"].toArray();
                                QMap<QString,QVariant> m;
                                QMap<QString,QMap<QString,QVariant>> m2;
                                for (int i = 0; i < arr1.count(); i++)
                                {
                                    QJsonObject arrObj = arr1[i].toObject();
                                    m.insert("type",arrObj["type"].toString());
                                    m.insert("primary",arrObj["primary"].toBool());
                                    m.insert("allownull",arrObj["allownull"].toBool());
                                    m.insert("unique",arrObj["unique"].toBool());
                                    m2.insert(arrObj["name"].toString(),m);
                                }
                                f.insert(tablename,m2);
                            }
                            else{
                                qDebug()<<obj["desc"];
                            }
                        });
                    }
                }
                else
                {
                    qDebug()<<obj["desc"];
                }
            });
            // 获取所有关系
            // 发送post请求
            QNetworkRequest request1;
            request1.setUrl(QUrl(URL_DEFINE_ASK_ALLRELATION));
            request1.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
            QNetworkReply *reply1 = manager->post(request1, postData);
            connect(reply1, &QNetworkReply::finished, [=]()
            {
                QJsonDocument replyJson = parseReply(reply1);
                //解析返回数据
                QJsonObject obj = replyJson.object();
                // 判断连接是否正常
                if(obj["code"]=="100"){
                    QJsonArray arr=obj["relation"].toArray();
                    for (int i = 0; i < arr.count(); i++){
                        QJsonObject robj=arr[i].toObject();
                        QString pattern1=robj["pattern1"].toString();
                        QString pattern2=robj["pattern2"].toString();
                        QString rname=robj["name"].toString();
                        QString rtype=robj["type"].toString();
                        if(relationRecord.contains(pattern1)){
                            relationRecord[pattern1].insert(pattern2,QPair<QString,QString>{rname,rtype});
                        }
                        else{
                            relationRecord.insert(pattern1,QMap<QString,QPair<QString,QString>>{ {pattern2,{rname,rtype}} });
                        }
                    }
                }
                else
                {
                    qDebug()<<obj["desc"];
                }
            });
        }
        else if(row==0){
            //qDebug()<<"fieldrecord:"<<fieldRecord;
        }
    });
    //lkl
    QTreeWidgetItemIterator it_2(ui->treeWidget_2);
    QObject::connect(ui->treeWidget_2, &QTreeWidget::itemClicked, [&](QTreeWidgetItem*, int)
        {
            int row = ui->treeWidget_2->currentIndex().row();
            ui->stackedWidget_2->setCurrentIndex(row); });
    //lkl
}

void UIDemo3::initPanelWidget()
{
    //    ui->widgetPanel->setWidget(frms, 7);
    //    ui->widgetPanel->setMargin(3);
    //    ui->widgetPanel->setSpacing(3);
}

void UIDemo3::initTableWidget()
{
    ui->editTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget_collection->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget_collection->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
    ui->tableWidget_collection->horizontalHeader()->setSectionResizeMode(ui->tableWidget_collection->columnCount() - 1, QHeaderView::Stretch);
    // 定义空表表隐藏7,8列，设置为不可编辑模式
    ui->editTableWidget->setColumnHidden(7, true);
    ui->editTableWidget->setColumnHidden(8, true);
}

void UIDemo3::initMenu()
{
    QMenu *menu = new QMenu(this);
    //    menu->addAction("端口管理", this, SLOT(doMenu()));
    //    menu->addAction("设备管理", this, SLOT(doMenu()));
    //    menu->addAction("告警设置", this, SLOT(doMenu()));
    //    menu->addSeparator();
    //    menu->addAction("系统设置", this, SLOT(doMenu()));
    //    menu->addAction("修改密码", this, SLOT(doMenu()));
    //    menu->addSeparator();
    //    menu->addAction("同步间隔", this, SLOT(doMenu()));

    ui->btnMain->setPopupMode(QToolButton::InstantPopup);
    ui->btnMain->setMenu(menu);
}

void UIDemo3::doMenu()
{
    QAction *action = (QAction *)sender();
    QUIWidget::showMessageBoxInfo(QString("你选择了菜单 [%1]").arg(action->text()), 5);
}

void UIDemo3::on_btnMenu_Min_clicked()
{
    showMinimized();
}

void UIDemo3::on_btnMenu_Max_clicked()
{
    if (max)
    {
        this->setGeometry(location);
        this->setProperty("canMove", true);
    }
    else
    {
        location = this->geometry();
        this->setGeometry(qApp->desktop()->availableGeometry());
        this->setProperty("canMove", false);
    }

    max = !max;
}

void UIDemo3::on_btnMenu_Close_clicked()
{
    close();
}

void UIDemo3::on_btnDefine_clicked()
{
    ui->comboBox_tables->blockSignals(true);
    ui->comboBox_tables->clear();
    ui->comboBox_tables->blockSignals(false);
    ui->comboBox_tables->addItem("空白表");
    // 切换页面
    ui->stackedWidget->setCurrentIndex(1);
    ui->stackedWidget_define->setCurrentIndex(0);

    // 查询所有表
    QString user("test");
    QString token("test");
    QString md5("test");
    // 构造post数据
    QJsonObject json;
    json.insert("user", user);
    json.insert("token", token);
    json.insert("md5", md5);
    QJsonDocument document;
    document.setObject(json);
    QByteArray dataArray = document.toJson(QJsonDocument::Compact);
    // 发送post数据
    QByteArray postData = document.toJson(QJsonDocument::Compact);
    // 打印post数据
    qDebug() << json;
    // 发送post请求
    QNetworkRequest request;
    request.setUrl(QUrl(URL_DEFINE_LIST));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    QNetworkReply *reply = manager->post(request, postData);
    connect(reply, &QNetworkReply::finished, [=]()
    {
        QJsonDocument replyJson = parseReply(reply);
        //解析返回数据
        QJsonObject obj = replyJson.object();
        // 判断连接是否正常
        if(obj["code"]=="100"){
            QJsonArray arr=obj["tables"].toArray();
            for (int i = 0; i < arr.count(); i++)
                ui->comboBox_tables->addItem(arr[i].toString());
        }
        else{
            qDebug()<<obj["desc"];
        }
    });

}

void UIDemo3::on_btnCollect_clicked()
{
    ui->stackedWidget->setCurrentIndex(2);
}

void UIDemo3::on_btnAnalyse_clicked()//lkl
{
    //ui->stackedWidget->setCurrentIndex(3);
    ui->comboBox_gettables->blockSignals(true);
    ui->comboBox_gettables->clear();
    ui->comboBox_gettables->blockSignals(false);
    ui->comboBox_gettables->addItem("选择表");
    // 切换页面
    ui->stackedWidget->setCurrentIndex(3);
    // 查询所有表
    QString user("test");
    QString token("test");
    QString md5("test");
    // 构造post数据
    QJsonObject json;
    json.insert("user", user);
    json.insert("token", token);
    json.insert("md5", md5);
    QJsonDocument document;
    document.setObject(json);
    QByteArray dataArray = document.toJson(QJsonDocument::Compact);
    // 发送post数据
    QByteArray postData = document.toJson(QJsonDocument::Compact);
    // 打印post数据
    qDebug() << json;
    // 发送post请求
    QNetworkRequest request;
    request.setUrl(QUrl(URL_DEFINE_LIST));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    QNetworkReply* reply = manager->post(request, postData);
    connect(reply, &QNetworkReply::finished, [=]()
        {
            QJsonDocument replyJson = parseReply(reply);
            //解析返回数据
            QJsonObject obj = replyJson.object();
            // 判断连接是否正常
            if (obj["code"] == "100") {
                QJsonArray arr = obj["tables"].toArray();
                for (int i = 0; i < arr.count(); i++)
                    ui->comboBox_gettables->addItem(arr[i].toString());
            }
            else {
                qDebug() << obj["desc"];
            }
        });

}

void UIDemo3::on_addFieldButton_clicked()
{
    qDebug() << "addfield";
    int maxrow = ui->editTableWidget->rowCount();
    ui->editTableWidget->insertRow(maxrow);
    // 设置表格项:
    /*
    0: 名称：串
    1: 下拉框:smallint int bigint float double year time date datetime char varchar text
    2: 长度：串
    3：null：checkbox
    4: 主键:checkbox
    5: 唯一：checkbox
    6：默认：串
    */
    ui->editTableWidget->setItem(maxrow, 0, new QTableWidgetItem(""));
    ui->editTableWidget->setItem(maxrow, 2, new QTableWidgetItem(""));
    ui->editTableWidget->setItem(maxrow, 6, new QTableWidgetItem(""));
    // 修改需要的辅助信息
    ui->editTableWidget->setItem(maxrow, 7, new QTableWidgetItem(""));
    ui->editTableWidget->setItem(maxrow, 8, new QTableWidgetItem(""));
    ui->editTableWidget->item(maxrow, 7)->setFlags(ui->editTableWidget->item(maxrow, 7)->flags() & ~Qt::ItemIsEditable);
    ui->editTableWidget->item(maxrow, 8)->setFlags(ui->editTableWidget->item(maxrow, 8)->flags() & ~Qt::ItemIsEditable);
    QComboBox *tmpq = new QComboBox(this);
    tmpq->addItem("请选择");
    tmpq->addItem("int");
    tmpq->addItem("float");
    tmpq->addItem("double");
    tmpq->addItem("datetime");
    tmpq->addItem("char");
    tmpq->addItem("varchar");
    tmpq->addItem("text");
    //    tmpq->addItem("year");
    //    tmpq->addItem("time");
    //    tmpq->addItem("date");
    //    tmpq->addItem("smallint");
    //    tmpq->addItem("bigint");
    ui->editTableWidget->setCellWidget(maxrow, 1, tmpq);
    QGridLayout *glayout1 = new QGridLayout();
    QGridLayout *glayout2 = new QGridLayout();
    QGridLayout *glayout3 = new QGridLayout();
    QCheckBox *tmpc1 = new QCheckBox(this);
    QCheckBox *tmpc2 = new QCheckBox(this);
    QCheckBox *tmpc3 = new QCheckBox(this);
    tmpc1->setCheckState(Qt::Checked);
    glayout1->addWidget(tmpc1);
    glayout2->addWidget(tmpc2);
    glayout3->addWidget(tmpc3);
    glayout1->setAlignment(tmpc1, Qt::AlignCenter);
    glayout2->setAlignment(tmpc2, Qt::AlignCenter);
    glayout3->setAlignment(tmpc3, Qt::AlignCenter);
    QWidget *w1 = new QWidget(this);
    QWidget *w2 = new QWidget(this);
    QWidget *w3 = new QWidget(this);
    w1->setLayout(glayout1);
    w2->setLayout(glayout2);
    w3->setLayout(glayout3);
    ui->editTableWidget->setCellWidget(maxrow, 3, w1);
    ui->editTableWidget->setCellWidget(maxrow, 4, w2);
    ui->editTableWidget->setCellWidget(maxrow, 5, w3);
    ui->editTableWidget->setRowHeight(maxrow, 50);

    // 添加修改类型
    if (ui->comboBox_tables->currentText() != "空白表")
    {
        ui->editTableWidget->item(maxrow, 7)->setText("待添加");
    }
    // 实现主键唯一效果
    setPrimaryKeyUniqueInTable(maxrow);
    // 更新
    ui->editTableWidget->update();
    return;
}

void UIDemo3::on_delFieldButton_clicked()
{
    qDebug() << "delfield";
    int now_row = ui->editTableWidget->currentRow();
    // 修改数据模式且为原有属性时，修改类型为待删除
    if (ui->comboBox_tables->currentText() != "空白表" && ui->editTableWidget->item(now_row, 8)->text() != "")
    {
        ui->editTableWidget->item(now_row, 7)->setText("待删除");
    }
    else
    {
        ui->editTableWidget->removeRow(now_row);
    }
    return;
}

/*
# post数据格式
{
    user:"xxxx",
    token:"xxxx",
    md5:"xxxx",
    table:
    {
        name:"xxx",
        field:
        [
            {name:"",type:"",length:0,allownull:true,primary:false,unique:false,default:xxx},
            {name:"",type:...}
        ]
    }
}
修改数据模式会在field中加入一个altertype属性，表示修改类型
*/
void UIDemo3::on_savePatternButton_clicked()
{

    ui->editTableWidget->update();
    // 0:新建数据模式 1：修改已有数据模式
    int type = 0;
    if (ui->comboBox_tables->currentText() != "空白表")
        type = 1;
    QString user("test");
    QString token("test");
    QString md5("test");
    QJsonArray fieldArray;
    int now_row = ui->editTableWidget->rowCount();
    if (type == 0)
    {
        // 新建数据模式的field构造
        //  构造属性表
        for (int i = 0; i < now_row; i++)
        {
            QJsonObject fieldObject;
            fieldObject.insert("name", ui->editTableWidget->item(i, 0)->text());
            fieldObject.insert("type", ((QComboBox *)ui->editTableWidget->cellWidget(i, 1))->currentText());
            fieldObject.insert("length", ui->editTableWidget->item(i, 2)->text().toInt());
            fieldObject.insert("allownull", ((QCheckBox *)ui->editTableWidget->cellWidget(i,3)->layout()->itemAt(0)->widget())->isChecked());
            fieldObject.insert("primary", ((QCheckBox *)ui->editTableWidget->cellWidget(i,4)->layout()->itemAt(0)->widget())->isChecked());
            fieldObject.insert("unique", ((QCheckBox *) ui->editTableWidget->cellWidget(i,5)->layout()->itemAt(0)->widget())->isChecked());
            if (ui->editTableWidget->item(i, 6)->text() == "")
                fieldObject.insert("default", "null");
            else{
                fieldObject.insert("default",ui->editTableWidget->item(i, 6)->text());
            }
            fieldArray.append(fieldObject);
        }
    }
    else
    {
        // 修改数据模式的field构造
        // 构造属性表
        for (int i = 0; i < now_row; i++)
        {
            QJsonObject fieldObject;
            QString edittype = ui->editTableWidget->item(i, 7)->text();
            if (edittype == "待修改")
            {
                QString lasttablename = ui->editTableWidget->item(i, 8)->text();
                fieldObject.insert("altertype", "change");
                // 修改属性名称单独处理
                fieldObject.insert("name", ui->editTableWidget->item(i, 8)->text());
                fieldObject.insert("newname", ui->editTableWidget->item(i, 0)->text());
                fieldObject.insert("type", ((QComboBox *)ui->editTableWidget->cellWidget(i, 1))->currentText());
                fieldObject.insert("length", ui->editTableWidget->item(i, 2)->text().toInt());
                fieldObject.insert("allownull", ((QCheckBox *)ui->editTableWidget->cellWidget(i,3)->layout()->itemAt(0)->widget())->isChecked());
                fieldObject.insert("primary", ((QCheckBox *)ui->editTableWidget->cellWidget(i,4)->layout()->itemAt(0)->widget())->isChecked());
                fieldObject.insert("unique", ((QCheckBox *)ui->editTableWidget->cellWidget(i,5)->layout()->itemAt(0)->widget())->isChecked());
                if (ui->editTableWidget->item(i, 6)->text() == "")
                    fieldObject.insert("default", "null");
                else
                    fieldObject.insert("default", ui->editTableWidget->item(i, 6)->text());
                qDebug()<<((QCheckBox *)ui->editTableWidget->cellWidget(i, 3)->children().at(0))->isChecked();
            }
            else if (edittype == "待添加")
            {
                fieldObject.insert("altertype", "add");
                fieldObject.insert("name", ui->editTableWidget->item(i, 0)->text());
                fieldObject.insert("type", ((QComboBox *)ui->editTableWidget->cellWidget(i, 1))->currentText());
                fieldObject.insert("length", ui->editTableWidget->item(i, 2)->text().toInt());
                fieldObject.insert("allownull", ((QCheckBox *)ui->editTableWidget->cellWidget(i,3)->layout()->itemAt(0)->widget())->isChecked());
                fieldObject.insert("primary", ((QCheckBox *)ui->editTableWidget->cellWidget(i,4)->layout()->itemAt(0)->widget())->isChecked());
                fieldObject.insert("unique", ((QCheckBox *)ui->editTableWidget->cellWidget(i,5)->layout()->itemAt(0)->widget())->isChecked());
                if (ui->editTableWidget->item(i, 6)->text() == "")
                    fieldObject.insert("default", "null");
                else
                    fieldObject.insert("default", ui->editTableWidget->item(i, 6)->text());
            }
            else if (edittype == "待删除")
            {
                fieldObject.insert("altertype", "drop");
                fieldObject.insert("name", ui->editTableWidget->item(i, 8)->text());
            }
            else
            {
            }
            fieldArray.append(fieldObject);
        }
    }
    //检查用户输入是否合法
    QList<QString> tmpname;
    QMap<QString,bool> defineCheck{
        {"primarykey",false},//必须有至少一个主键
        {"nametype",true},//字段必须有名称和类型
        {"uniquename",false},//名称不可重复
        {"fieldempty",false},//字段的总数不可为0
        {"tablename",false}//表名称不能为“空白表"
    };
    // 进行检查
    foreach (const QJsonValue &value, fieldArray) {
        QJsonObject obj=value.toObject();
        defineCheck["primarykey"]|=obj["primary"].toBool();
        defineCheck["nametype"]=defineCheck["nametype"]&&(obj["name"].toString()!="")&&(obj["type"].toString()!="请选择");
        tmpname.push_back(obj["name"].toString());
    }
    defineCheck["fieldempty"]=fieldArray.size()>0?true:false;
    int tmplen=tmpname.length();
    tmpname.removeDuplicates();
    defineCheck["uniquename"]=tmplen==tmpname.length()?1:0;
    // 构造表
    QString tableName = ui->tableNameLineEdit->text();
    defineCheck["tablename"]=tableName=="空白表"?0:1;
    // 发送之前进行错误检查
    foreach(QString key ,defineCheck.keys()){
        // 存在错误，直接生成提示框并返回
        if(!defineCheck[key]){
            errorMessageBox("define",key);
            return;
        }
    }

    QJsonObject tableObject;
    tableObject.insert("name", tableName);
    tableObject.insert("field", fieldArray);
    // 构造post数据
    QJsonObject postObject;
    postObject.insert("user", user);
    postObject.insert("token", token);
    postObject.insert("md5", md5);
    postObject.insert("table", tableObject);
    // 转换为bytearray，可以进行post
    QJsonDocument postDocument;
    postDocument.setObject(postObject);
    QByteArray postData = postDocument.toJson(QJsonDocument::Compact);
    // 打印post数据
    qDebug() << postObject;

    // 发送post请求

    QNetworkRequest request;
    if (type == 0)
    {
        request.setUrl(QUrl(URL_DEFINE_CREATE));
    }
    else
    {
        request.setUrl(QUrl(URL_DEFINE_ALTER));
    }

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    QNetworkReply *reply = manager->post(request, postData);

    connect(reply, &QNetworkReply::finished, [=](){
        QJsonDocument replyJson = parseReply(reply);
        QJsonObject obj=replyJson.object();
        if(obj["code"]=="100"){
            QMessageBox::information(this,  "数据模式定义","保存成功");
        }
        else{
            QMessageBox::critical(this,  "数据模式定义","保存失败");
        }
    });

    return;
}

QJsonDocument UIDemo3::parseReply(QNetworkReply *reply)
{
    qDebug() << reply->errorString();
    qDebug() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).value<QString>();
    QByteArray responseData = reply->readAll();
    qDebug() << responseData;

    QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
    QJsonObject jsonObj = jsonDoc.object();

    QJsonParseError jsonError;
    QJsonDocument doucment = QJsonDocument::fromJson(responseData, &jsonError);
    if (jsonError.error != QJsonParseError::NoError)
    {
        qDebug() << QStringLiteral("解析Json失败");
        qDebug() << jsonError.errorString();
    }

    // 解析Json
    if (doucment.isObject())
    {
        QJsonObject obj = doucment.object();
        QJsonValue value;
        if (obj.contains("data"))
        {
            value = obj.take("data");
            qDebug() << value;
            if (value.isString())
            {
                QString data = value.toString();
                qDebug() << data;
            }
        }
    }
    return doucment;
}

/*#
post数据格式  格式同上
{
    user:"xxxx",
    token:"xxxx",
    md5:"xxxx",
    table:
    {
        name:"xxx"
    }
}*/
void UIDemo3::on_comboBox_tables_currentIndexChanged(int)
{
    // 更新combox_othertables
    ui->comboBox_otherTable->blockSignals(true);
    ui->comboBox_otherTable->clear();
    ui->comboBox_otherTable->blockSignals(false);
    ui->comboBox_otherTable->addItem("请选择");

    // 清空fieldrecord
    fieldRecord.clear();
    //  逐行清空tablewidget
    while (ui->editTableWidget->rowCount() > 0)
        ui->editTableWidget->removeRow(ui->editTableWidget->rowCount() - 1);
    QString tablename = ui->comboBox_tables->currentText();
    ui->tableNameLineEdit->setText(tablename);
    if (tablename == "空白表")
    {
        // 隐藏7,8列
        ui->editTableWidget->setColumnHidden(7, true);
        ui->editTableWidget->setColumnHidden(8, true);
        // 更新
        ui->editTableWidget->update();
        ui->delPatternButton->setDisabled(true);
        return;
    }
    // 显示7,8列
    ui->editTableWidget->setColumnHidden(7, false);
    ui->editTableWidget->setColumnHidden(8, false);
    ui->delPatternButton->setDisabled(false);
    // 构造post数据
    QString user("test");
    QString token("test");
    QString md5("test");
    QJsonObject tableObject;
    tableObject.insert("name", tablename);
    QJsonObject postObject;
    postObject.insert("user", user);
    postObject.insert("token", token);
    postObject.insert("md5", md5);
    postObject.insert("table", tableObject);
    // 转换为bytearray，可以进行post
    QJsonDocument postDocument;
    postDocument.setObject(postObject);
    QByteArray postData = postDocument.toJson(QJsonDocument::Compact);
    // 打印post数据
    qDebug() << postObject;
    // 修改tableNameLineEdit显示
    ui->tableNameLineEdit->setText(tablename);
    // 发送请求,查询表的属性
    QNetworkRequest request;
    request.setUrl(QUrl(URL_DEFINE_DETAIL));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    QNetworkReply *reply = manager->post(request, postData);
    connect(reply, &QNetworkReply::finished, [=]()
    {
        // 解析返回的数据并获取对象
        QJsonDocument replyJson = parseReply(reply);
        QJsonObject obj = replyJson.object();
        // 判断连接是否正常
        if(obj["code"]=="100"){
            QJsonValue userValue=obj.value("table");
            QJsonObject userObj = userValue.toObject();
            QJsonArray arr=userObj["field"].toArray();
            for (int i = 0; i < arr.count(); i++)
            {
                on_addFieldButton_clicked();
                int nowrow = ui->editTableWidget->rowCount()-1;
                QJsonObject arrObj = arr[i].toObject();
                //0:name 1:type 2:length 3:null 4:primriay 5:unique 6:default 7:待修改 8:原字段
                ui->editTableWidget->item(nowrow,0)->setText(arrObj["name"].toString());
                ui->editTableWidget->item(nowrow,6)->setText(arrObj["default"].toString());
                ui->editTableWidget->item(nowrow,2)->setText(QString::number(arrObj["length"].toDouble()));
                QCheckBox* c3= (QCheckBox*)(ui->editTableWidget->cellWidget(nowrow,3)->layout()->itemAt(0)->widget());
                c3->setChecked(arrObj["allownull"].toBool());
                QCheckBox* c4= (QCheckBox*)(ui->editTableWidget->cellWidget(nowrow,4)->layout()->itemAt(0)->widget());
                if(arrObj["primary"].toBool()==true)
                    c4->click();
                QCheckBox* c5= (QCheckBox*)(ui->editTableWidget->cellWidget(nowrow,5)->layout()->itemAt(0)->widget());
                c5->setChecked(arrObj["unique"].toBool());
                QComboBox* c1= (QComboBox*)(ui->editTableWidget->cellWidget(nowrow,1));
                c1->setCurrentText(arrObj["type"].toString());
                // 添加备份辅助信息
                ui->editTableWidget->item(nowrow,7)->setText("待修改");
                ui->editTableWidget->item(nowrow,8)->setText(arrObj["name"].toString());
                nowrow++;
            }
        }
        else{
            qDebug()<<obj["desc"];
        }
        // 将返回的表各项属性填入editTableWidget中
        qDebug() << "showtable";
        // 更新
        ui->editTableWidget->update(); });

    // 更新combox_othertables



    // 构造post数据
    QJsonObject json;
    json.insert("user", user);
    json.insert("token", token);
    json.insert("md5", md5);
    QJsonDocument document;
    document.setObject(json);
    // 发送post数据
    QByteArray postData1 = document.toJson(QJsonDocument::Compact);
    // 打印post数据
    qDebug() << json;
    // 发送post请求
    QNetworkRequest request1;
    request1.setUrl(QUrl(URL_DEFINE_LIST));
    request1.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    QNetworkReply *reply1 = manager->post(request1, postData1);
    connect(reply1, &QNetworkReply::finished, [=]()
    {
        QJsonDocument replyJson = parseReply(reply1);
        //解析返回数据
        QJsonObject obj = replyJson.object();
        // 判断连接是否正常
        if(obj["code"]=="100"){
            QJsonArray arr=obj["tables"].toArray();
            for (int i = 0; i < arr.count(); i++){
                if(arr[i].toString()!=tablename)
                    ui->comboBox_otherTable->addItem(arr[i].toString());
            }

        }
        else{
            qDebug()<<obj["desc"];
        }
    });

}

void UIDemo3::setPrimaryKeyUniqueInTable(int row)
{
    QCheckBox *checkbox = (QCheckBox *)(ui->editTableWidget->cellWidget(row, 4)->layout()->itemAt(0)->widget());
    connect(checkbox, &QCheckBox::clicked, [=]()
    {
        for (int i = 0; i < ui->editTableWidget->rowCount(); ++i)
        {
            if (i != row)
            {
                QCheckBox *other4 = (QCheckBox *)(ui->editTableWidget->cellWidget(i, 4)->layout()->itemAt(0)->widget());
                other4->setChecked(false);
                QCheckBox *other5 = (QCheckBox *)(ui->editTableWidget->cellWidget(i, 5)->layout()->itemAt(0)->widget());
                other5->setDisabled(false);
                QCheckBox *other3 = (QCheckBox *)(ui->editTableWidget->cellWidget(i, 3)->layout()->itemAt(0)->widget());
                other3->setDisabled(false);
            }
            else
            {
                QCheckBox *c3 = (QCheckBox *)(ui->editTableWidget->cellWidget(row, 3)->layout()->itemAt(0)->widget());
                c3->setDisabled(true);
                c3->setChecked(false);
                QCheckBox *c5 = (QCheckBox *)(ui->editTableWidget->cellWidget(row, 5)->layout()->itemAt(0)->widget());
                c5->setChecked(true);
                c5->setDisabled(true);
                QCheckBox *c4 = (QCheckBox *)(ui->editTableWidget->cellWidget(row, 4)->layout()->itemAt(0)->widget());
                c4->setChecked(true);
            }
        }
    });
    return;
}
/*
# post数据格式  格式同上
{
    user:"xxxx",
    token:"xxxx",
    md5:"xxxx",
    table:
    {
        name:"xxx"
    }
}
*/
// 删除表
void UIDemo3::on_delPatternButton_clicked()
{
    // 构造post数据
    QString tablename = ui->comboBox_tables->currentText();
    QString user("test");
    QString token("test");
    QString md5("test");
    QJsonObject tableObject;
    tableObject.insert("name", tablename);
    QJsonObject postObject;
    postObject.insert("user", user);
    postObject.insert("token", token);
    postObject.insert("md5", md5);
    postObject.insert("table", tableObject);
    // 转换为bytearray，可以进行post
    QJsonDocument postDocument;
    postDocument.setObject(postObject);
    QByteArray postData = postDocument.toJson(QJsonDocument::Compact);
    // 打印post数据
    qDebug() << postObject;
    // 发送请求,查询表的属性
    QNetworkRequest request;
    request.setUrl(QUrl(URL_DEFINE_DEL));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    QNetworkReply *reply = manager->post(request, postData);
    connect(reply, &QNetworkReply::finished, [=]()
    {
        QJsonDocument replyJson = parseReply(reply);
        QJsonObject obj=replyJson.object();
        if(obj["code"]=="100"){
            QMessageBox::information(this,  "数据模式删除","删除成功");
        }
        else{
            QMessageBox::critical(this,  "数据模式删除","删除失败");
        }
    });
}

void UIDemo3::on_saveRelationButton_clicked(){
    if(ui->relationLine->text()==""){
        errorMessageBox("define","norelationname");
    }
    else if(ui->comboBox_relation->currentText()=="请选择类型"){
        errorMessageBox("define","norelationtype");
    }
    else if(ui->comboBox_otherTable->currentText()=="请选择"){
        errorMessageBox("define","noothertable");
    }
    QString user("test");
    QString token("test");
    QString md5("test");
    QJsonObject relation;
    relation.insert("name",ui->relationLine->text());
    QString relationtext=ui->comboBox_relation->currentText();
    if(relationtext=="一对多"){
        relation.insert("type","1-n");
    }
    else if(relationtext=="多对一"){
        relation.insert("type","n-1");
    }
    else if(relationtext=="一对一"){
        relation.insert("type","1-1");
    }
    else if(relationtext=="多对多"){
        relation.insert("type","n-n");
    }
    relation.insert("pattern1",ui->tableNameLineEdit->text());
    relation.insert("pattern2",ui->comboBox_otherTable->currentText());
    QJsonObject postObject;
    postObject.insert("user", user);
    postObject.insert("token", token);
    postObject.insert("md5", md5);
    postObject.insert("relation", relation);
    // 转换为bytearray，可以进行post
    QJsonDocument postDocument;
    postDocument.setObject(postObject);
    QByteArray postData = postDocument.toJson(QJsonDocument::Compact);
    // 打印post数据
    qDebug() << postObject;
    // 发送请求,查询表的属性
    QNetworkRequest request;
    request.setUrl(QUrl(URL_DEFINE_CREATE_RELATION));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    QNetworkReply *reply = manager->post(request, postData);
    connect(reply, &QNetworkReply::finished, [=]()
    {
        QJsonDocument replyJson = parseReply(reply);
        QJsonObject obj=replyJson.object();
        if(obj["code"]=="100"){
            QMessageBox::information(this,  "数据模式关系","保存成功");
        }
        else{
            QMessageBox::critical(this,  "数据模式关系","保存失败");
        }
    });


}



//lkl

void UIDemo3::on_addrecord_clicked()
{
    ui->tableWidget_analyse->verticalHeader()->setVisible(false);
    QString tablename = ui->comboBox_gettables->currentText();
    if (tablename == "选择表")
    {
        QMessageBox::warning(this, "警告", "请先选择表");
        return;
    }
    qDebug() << "addRecord";
    int maxrow = ui->tableWidget_analyse->rowCount();
    ui->tableWidget_analyse->insertRow(maxrow);
    ui->tableWidget_analyse->setItem(maxrow, 1, new QTableWidgetItem(""));
    ui->tableWidget_analyse->setItem(maxrow, 2, new QTableWidgetItem(""));
    ui->tableWidget_analyse->setItem(maxrow, 3, new QTableWidgetItem(""));
    ui->tableWidget_analyse->setItem(maxrow, 4, new QTableWidgetItem(""));
    ui->tableWidget_analyse->setItem(maxrow, 5, new QTableWidgetItem(""));
    ui->tableWidget_analyse->setItem(maxrow, 6, new QTableWidgetItem(""));
    if (maxrow == 0)
    {
        ui->tableWidget_analyse->setItem(maxrow, 0, new QTableWidgetItem(""));
        return;
    }
    QTableWidgetItem* item = new QTableWidgetItem();
    item->setTextAlignment(Qt::AlignCenter);
    item->setFont(ui->tableWidget_analyse->font());
    item->setCheckState(Qt::Unchecked);
    ui->tableWidget_analyse->setItem(maxrow, 0, item);

    return;
}

void UIDemo3::on_delrecord_clicked()
{
    qDebug() << "delRecord";
    QString tablename = ui->comboBox_gettables->currentText();
    if (tablename == "选择表")
    {
        QMessageBox::warning(this, "警告", "请先选择表");
        return;
    }
    QString user("test");
    QString token("test");
    QString md5("test");
    QString type("del");
    QJsonObject tableObject;
    QJsonObject tableObject_1;
    tableObject.insert("name", tablename);
    tableObject_1.insert("name", tablename);
    QJsonArray detailArray;
    QJsonArray array;
    int temp[100];
    int temp_1=0;
    int now_row = ui->tableWidget_analyse->rowCount();
    ui->tableWidget_analyse->verticalHeader()->setVisible(false);
    for (int i = 0; i <now_row; i++)
        {
            if (ui->tableWidget_analyse->item(i,0)->checkState() == Qt::Checked) //选中
            {
                temp[i]=1;
                temp_1=1;
            }
        }
    //没有记录被选中点击删除，出警告
    if(temp_1==0)
    {
        QMessageBox::warning(this, "警告", "请先选择需删除的行再进行操作");
    }
    else{
        for(int i=0;i<now_row;i++)
        {
            if(temp[i]==1)
            {
                qDebug() << i;
                for (int j = 0; j < field_num; j++)
                {
                    array.append(ui->tableWidget_analyse->item(i, j + 1)->text());
                }
                detailArray.append(array);
                for (int j = 0; j < field_num; j++)
                {
                    array.removeFirst();
                }
            }

        }
    }
    tableObject.insert("detail", detailArray);
    QJsonObject json;
    QJsonObject json_1;
    json.insert("user", user);
    json.insert("token", token);
    json.insert("md5", md5);
    json.insert("type", type);
    json.insert("table", tableObject);
    QJsonDocument document;
    document.setObject(json);
    QByteArray dataArray = document.toJson(QJsonDocument::Compact);
    // 发送post数据
    QByteArray postData = document.toJson(QJsonDocument::Compact);
    // 打印post数据
    qDebug() << json;
    qDebug() << json_1;
    // 发送post请求
    QNetworkRequest request;
    request.setUrl(QUrl(URL_ANALYSE_RECORD));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    json_1.insert("user", user);
    json_1.insert("token", token);
    json_1.insert("md5", md5);
    json_1.insert("table", tableObject_1);
    QJsonDocument document_1;
    document_1.setObject(json_1);
    QByteArray dataArray_1 = document_1.toJson(QJsonDocument::Compact);
    // 发送post数据
    QByteArray postData_1 = document_1.toJson(QJsonDocument::Compact);
    // 打印post数据
    QNetworkRequest request_1;
    request_1.setUrl(QUrl(URL_ANALYSE_DETAIL));
    request_1.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    QNetworkReply* reply_1 = manager->post(request_1, postData_1);

    connect(reply_1, &QNetworkReply::finished, [=]()
        {
            QJsonDocument replyJson = parseReply(reply_1);
            //解析返回数据
            QJsonObject obj = replyJson.object();
            QJsonObject tab = obj["table"].toObject();
            // 判断连接是否正常
            if (obj["code"] == "100") {

                while (ui->tableWidget_analyse->rowCount() > 0)
                {
                    ui->tableWidget_analyse->removeRow(ui->tableWidget_analyse->rowCount() - 1);
                }
                on_addrecord_clicked();
                ui->tableWidget_analyse->item(0, 0)->setText("属性");
                QJsonArray field = tab["fields"].toArray();
                // for (int i = 0; i < tab["fieldNum"].toInt(); i++)
                for (int i = 0; i < field.count(); i++)
                {
                    ui->tableWidget_analyse->item(0, i + 1)->setText(field[i].toString());
                }
                QJsonArray det = tab["detail"].toArray();
                record_num = det.count();
                //record_num=tab["recordNum"].toInt();
                //for (int i = 0; i < tab["fieldNum"].toInt(); i++)
                for (int i = 0; i < det.count(); i++)
                {
                    on_addrecord_clicked();
                    int nowrow = ui->tableWidget_analyse->rowCount() - 1;
                    QJsonArray det_1 = det[i].toArray();
                    qDebug() << det_1;
                    for (int j = 0; j < field.count(); j++)
                    {
                        //qDebug() << det_1[j];
                        ui->tableWidget_analyse->item(nowrow, j + 1)->setText(det_1[j].toString());
                    }
                }
            }
            else {
                qDebug() << obj["desc"];
            }

            // 将返回的表各项属性填入editTableWidget中

            // 更新
            ui->tableWidget_analyse->update(); });
    qDebug() << "showtable";
    return;
}
//lkl


////lkl
//void UIDemo3::on_selectdata_clicked()
//{
//    ui->stackedWidget_2->setCurrentIndex(3);
//}

void UIDemo3::on_back_clicked()
{
    ui->comboBox_connect->setCurrentIndex(0);
    ui->comboBox_attribute->setCurrentIndex(0);
    ui->comboBox_symbol->setCurrentIndex(0);
    ui->lineEdit_range->clear();
    ui->stackedWidget_2->setCurrentIndex(0);
    con = "";
    num = 0;
}

//void UIDemo3::on_confirm_clicked()
//{
//    ui->stackedWidget_2->setCurrentIndex(0);
//}

//xym 三次修改:切换页面 显示已创建表单 显示可选择表单
void UIDemo3::on_treeWidget_3_itemClicked(QTreeWidgetItem *item, int column)
{
    if(item->text(column)=="创建表单")
    {
        //ui->stackedWidget_3->setCurrentIndex(0);
        const QUrl regUrl(QLatin1String("http://124.70.0.60:8080/#/"));
        QDesktopServices::openUrl(regUrl);
    }
    if(item->text(column)=="查看已生成表单")
    {
        ui->stackedWidget_3->setCurrentIndex(1);
        //  逐行清空tablewidget
        while (ui->tableWidget_collection->rowCount() > 0)
        {
            ui->tableWidget_collection->removeRow(ui->tableWidget_collection->rowCount() - 1);
        }

        // 查询所有表单
        QString user("test");
        QString token("test");
        QString md5("test");
        // 构造post数据
        QJsonObject json;
        json.insert("user", user);
        json.insert("token", token);
        json.insert("md5", md5);
        QJsonDocument document;
        document.setObject(json);

        // 发送post数据
        QByteArray postData = document.toJson(QJsonDocument::Compact);
        // 打印post数据
        qDebug() << json;
        // 发送post请求
        QNetworkRequest request;
        request.setUrl(QUrl(URL_COLLECTION_GETFORMINFO));
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
        QNetworkReply* reply = manager->post(request, postData);
        connect(reply, &QNetworkReply::finished, [=]()
        {
            QJsonDocument replyJson = parseReply(reply);
            //解析返回数据
            QJsonObject obj = replyJson.object();

            // 判断连接是否正常
            if (obj["code"] == "100") {
                QJsonArray form = obj["forms"].toArray();
                qDebug() << form;

                for (int i = 0; i < form.count(); i++)
                {
                    //on_addrecord_clicked();
                    int maxrow = ui->tableWidget_collection->rowCount();
                    ui->tableWidget_collection->insertRow(maxrow);
                    ui->tableWidget_collection->setItem(maxrow, 1, new QTableWidgetItem(""));
                    ui->tableWidget_collection->setItem(maxrow, 2, new QTableWidgetItem(""));
                    ui->tableWidget_collection->setItem(maxrow, 3, new QTableWidgetItem(""));

                    int nowrow = ui->tableWidget_collection->rowCount() - 1;
                    QJsonObject det_1 = form[i].toObject();
                    //qDebug() << det_1;
                    ui->tableWidget_collection->item(nowrow, 1)->setText(det_1["id"].toString());
                    ui->tableWidget_collection->item(nowrow, 2)->setText(det_1["name"].toString());
                    ui->tableWidget_collection->item(nowrow, 3)->setText(det_1["url"].toString());
                   // qDebug() << det_1["id"].toString();
                    QTableWidgetItem* item = new QTableWidgetItem();
                    item->setTextAlignment(Qt::AlignCenter);
                    item->setFont(ui->tableWidget_collection->font());
                    item->setCheckState(Qt::Unchecked);
                    ui->tableWidget_collection->setItem(maxrow, 0, item);
                 }
                //设置表格数据区内的所有单元格都不允许编辑
                //ui->tableWidget_collection->setEditTriggers(QAbstractItemView::NoEditTriggers);
            }
            else {
                qDebug() << obj["desc"];
            }
        });
    }
    if(item->text(column)=="查看指定表单填写详情")
    {
        ui->stackedWidget_3->setCurrentIndex(2);
        ui->comboBox_getforms->blockSignals(true);
        ui->comboBox_getforms->clear();
        ui->comboBox_getforms->blockSignals(false);
        ui->comboBox_getforms->addItem("选择表单(点击所选择的表单后请稍等)");

        // 查询所有表
        QString user("test");
        QString token("test");
        QString md5("test");
        // 构造post数据
        QJsonObject json;
        json.insert("user", user);
        json.insert("token", token);
        json.insert("md5", md5);
        QJsonDocument document;
        document.setObject(json);

        // 发送post数据
        QByteArray postData = document.toJson(QJsonDocument::Compact);
        // 打印post数据
        qDebug() << json;
        // 发送post请求
        QNetworkRequest request;
        request.setUrl(QUrl(URL_COLLECTION_GETFORMLIST));
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
        QNetworkReply* reply = manager->post(request, postData);
        connect(reply, &QNetworkReply::finished, [=]()
        {
            QJsonDocument replyJson = parseReply(reply);
            //解析返回数据
            QJsonObject obj = replyJson.object();
            // 判断连接是否正常
            if (obj["code"] == "100") {
                QJsonArray arr = obj["forms"].toArray();
                for (int i = 0; i < arr.count(); i++)
                    ui->comboBox_getforms->addItem(arr[i].toString());
            }
            else {
                qDebug() << obj["desc"];
            }
        });
    }
}

void UIDemo3::on_todesignlinkButton_clicked()
{
    ui->stackedWidget_3->setCurrentIndex(3);
}

void UIDemo3::errorMessageBox(QString moduleName,QString errorType){
    if(moduleName=="define"){
        QString title="数据模式定义输入错误";
        if(errorType=="primarykey") QMessageBox::critical(this, title,"必须有至少一个主键");
        else if(errorType=="nametype")QMessageBox::critical(this, title,"字段必须有名称和类型");
        else if(errorType=="uniquename")QMessageBox::critical(this, title,"名称不可重复");
        else if(errorType=="fieldempty")QMessageBox::critical(this, title,"字段的总数不可为0");
        else if(errorType=="tablename")QMessageBox::critical(this, title,"表名称不能为“空白表");
        else if(errorType=="norelationname")QMessageBox::critical(this, title,"关系要有名称哦！！");
        else if(errorType=="norelationtype")QMessageBox::critical(this, title,"关系要有类型哦！！");
        else if(errorType=="noothertable")QMessageBox::critical(this, title,"要选择一张其他的表哦！！");
    }
    return;
}


void UIDemo3::on_comboBox_gettables_currentIndexChanged(int)
{
    ui->tableWidget_analyse->verticalHeader()->setVisible(false);
    // 清空fieldrecord
    fieldRecord.clear();
    //  逐行清空tablewidget
    while (ui->tableWidget_analyse->rowCount() > 0)
    {
        ui->tableWidget_analyse->removeRow(ui->tableWidget_analyse->rowCount() - 1);
    }
    QString tablename = ui->comboBox_gettables->currentText();
       if (tablename == "选择表")
       {
           return;
       }

       // 查询所有表
       QString user("test");
       QString token("test");
       QString md5("test");
       QJsonObject tableObject;
       tableObject.insert("name", tablename);
       // 构造post数据
       QJsonObject json;
       json.insert("user", user);
       json.insert("token", token);
       json.insert("md5", md5);
       json.insert("table", tableObject);
       QJsonDocument document;
       document.setObject(json);
       QByteArray dataArray = document.toJson(QJsonDocument::Compact);
       // 发送post数据
       QByteArray postData = document.toJson(QJsonDocument::Compact);
       // 打印post数据
       qDebug() << json;
       // 发送post请求
       QNetworkRequest request;
       request.setUrl(QUrl(URL_ANALYSE_DETAIL));
       request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
       QNetworkReply* reply = manager->post(request, postData);
       connect(reply, &QNetworkReply::finished, [=]()
           {
               QJsonDocument replyJson = parseReply(reply);
               //解析返回数据
               QJsonObject obj = replyJson.object();
               QJsonObject tab = obj["table"].toObject();
               // 判断连接是否正常
               if (obj["code"] == "100") {
                   on_addrecord_clicked();
                   ui->tableWidget_analyse->item(0, 0)->setText("属性");
                   QJsonArray field = tab["fields"].toArray();
                   // for (int i = 0; i < tab["fieldNum"].toInt(); i++)
                   field_num = field.count();
                   //field_num=tab["fieldNum"].toInt();
                   for (int i = 0; i < field.count(); i++)
                   {
                       ui->tableWidget_analyse->item(0, i + 1)->setText(field[i].toString());
                   }
                   QJsonArray det = tab["detail"].toArray();
                   record_num = det.count();
                   //record_num=tab["recordNum"].toInt();
                   //for (int i = 0; i < tab["fieldNum"].toInt(); i++)
                   for (int i = 0; i < det.count(); i++)
                   {
                       on_addrecord_clicked();
                       int nowrow = ui->tableWidget_analyse->rowCount() - 1;
                       QJsonArray det_1 = det[i].toArray();
                       qDebug() << det_1;
                       for (int j = 0; j < field.count(); j++)
                      {
                           //qDebug() << det_1[j];
                            ui->tableWidget_analyse->item(nowrow, j+1)->setText(det_1[j].toString());
                       }
                       }
               }
               else {
                   qDebug() << obj["desc"];
               }
           });
}

void UIDemo3::on_lineEdit_addition_textChanged() {
    con= ui->lineEdit_addition->text();
    ui->lineEdit_addition->setText(con);
}

void UIDemo3::on_filtratedata_clicked()
{
    ui->tableWidget_analyse->verticalHeader()->setVisible(false);


    // 查询所有表
    QString tablename = ui->comboBox_gettables->currentText();
    if (tablename == "选择表")
    {
        QMessageBox::warning(this, "警告", "请先选择表");
        return;
    }

    QString user("test");
    QString token("test");
    QString md5("test");
    QJsonObject tableObject;
    tableObject.insert("name", tablename);
    // 构造post数据
    QJsonObject json;
    json.insert("user", user);
    json.insert("token", token);
    json.insert("md5", md5);
    json.insert("table", tableObject);
    QJsonDocument document;
    document.setObject(json);
    QByteArray dataArray = document.toJson(QJsonDocument::Compact);
    // 发送post数据
    QByteArray postData = document.toJson(QJsonDocument::Compact);
    // 打印post数据
    qDebug() << json;
    // 发送post请求
    QNetworkRequest request;
    request.setUrl(QUrl(URL_ANALYSE_DETAIL));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    QNetworkReply* reply = manager->post(request, postData);
    // 切换页面
    ui->stackedWidget_2->setCurrentIndex(3);
    connect(reply, &QNetworkReply::finished, [=]()
        {
            QJsonDocument replyJson = parseReply(reply);
            //解析返回数据
            QJsonObject obj = replyJson.object();
            QJsonObject tab = obj["table"].toObject();

            // 判断连接是否正常
            if (obj["code"] == "100") {
                QJsonArray field = tab["fields"].toArray();
                ui->comboBox_attribute->clear();
                ui->comboBox_attribute->addItem("");
                //for (int i = 0; i < tab["fieldNum"].toInt(); i++)
                for (int i = 0; i < field.count(); i++)

                    ui->comboBox_attribute->addItem(field[i].toString());
            }
            else {
                qDebug() << obj["desc"];
            }
        });
}

void UIDemo3::on_ascsort_clicked()
{
    ui->tableWidget_analyse->verticalHeader()->setVisible(false);
    QString tablename = ui->comboBox_gettables->currentText();
    if (tablename == "选择表")
    {
        QMessageBox::warning(this, "警告", "请先选择表");
        return;
    }
    QJsonObject tableObject;
    QList<QTableWidgetItem*> items = ui->tableWidget_analyse->selectedItems();
    if (!items.empty())
    {
    qDebug() << "升序排列";
    int col = ui->tableWidget_analyse->column(items.at(0));
    QString fieldname = ui->tableWidget_analyse->item(0, col)->text();
    tableObject.insert("attribute", fieldname);
    qDebug() << fieldname;
    }

    else
    {

        QMessageBox::warning(this, "警告", "请先选择一列再进行操作");
    }
    QString user("test");
    QString token("test");
    QString md5("test");
    QString type("asc");

    tableObject.insert("name", tablename);

    QJsonObject json;
    json.insert("user", user);
    json.insert("token", token);
    json.insert("md5", md5);
    json.insert("sortType", type);
    json.insert("table", tableObject);
    QJsonDocument document;
    document.setObject(json);
    QByteArray dataArray = document.toJson(QJsonDocument::Compact);
    // 发送post数据
    QByteArray postData = document.toJson(QJsonDocument::Compact);
    // 打印post数据
    qDebug() << json;
    // 发送post请求
    QNetworkRequest request;
    request.setUrl(QUrl(URL_ANALYSE_SORT));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    QNetworkReply* reply = manager->post(request, postData);

    connect(reply, &QNetworkReply::finished, [=]()
        {

            QJsonDocument replyJson = parseReply(reply);
            //解析返回数据
            QJsonObject obj = replyJson.object();
            QJsonObject tab = obj["table"].toObject();
            // 判断连接是否正常
            if (obj["code"] == "100") {

                while (ui->tableWidget_analyse->rowCount() > 0)
                {
                    ui->tableWidget_analyse->removeRow(ui->tableWidget_analyse->rowCount() - 1);
                }
                on_addrecord_clicked();
                ui->tableWidget_analyse->item(0, 0)->setText("属性");
                QJsonArray field = tab["fields"].toArray();
                // for (int i = 0; i < tab["fieldNum"].toInt(); i++)
                for (int i = 0; i < field.count(); i++)
                {
                    ui->tableWidget_analyse->item(0, i + 1)->setText(field[i].toString());
                }
                QJsonArray det = tab["detail"].toArray();
                //for (int i = 0; i < tab["fieldNum"].toInt(); i++)
                for (int i = 0; i < det.count(); i++)
                {
                    on_addrecord_clicked();
                    int nowrow = ui->tableWidget_analyse->rowCount() - 1;
                    QJsonArray det_1 = det[i].toArray();
                    qDebug() << det_1;
                    for (int j = 0; j < field.count(); j++)
                    {
                        //qDebug() << det_1[j];
                        ui->tableWidget_analyse->item(nowrow, j+1)->setText(det_1[j].toString());
                    }
                }
            }
            else {
                qDebug() << obj["desc"];
            }});
    qDebug() << "showtable";
}

void UIDemo3::on_descsort_clicked()
{
    ui->tableWidget_analyse->verticalHeader()->setVisible(false);
    QString tablename = ui->comboBox_gettables->currentText();
    if (tablename == "选择表")
    {
        QMessageBox::warning(this, "警告", "请先选择表");
        return;
    }
    QJsonObject tableObject;
    QList<QTableWidgetItem*> items = ui->tableWidget_analyse->selectedItems();
    if (!items.empty())
    {
        qDebug() << "降序排列";
        int col = ui->tableWidget_analyse->column(items.at(0));
        QString fieldname = ui->tableWidget_analyse->item(0,col)->text();
        tableObject.insert("attribute", fieldname);
        qDebug() << fieldname;

    }

    else
    {

        QMessageBox::warning(this, "警告", "请先选择一列再进行操作");
    }
    QString user("test");
    QString token("test");
    QString md5("test");
    QString type("desc");

    tableObject.insert("name", tablename);

    QJsonObject json;
    json.insert("user", user);
    json.insert("token", token);
    json.insert("md5", md5);
    json.insert("sortType", type);
    json.insert("table", tableObject);
    QJsonDocument document;
    document.setObject(json);
    QByteArray dataArray = document.toJson(QJsonDocument::Compact);
    // 发送post数据
    QByteArray postData = document.toJson(QJsonDocument::Compact);
    // 打印post数据
    qDebug() << json;
    // 发送post请求
    QNetworkRequest request;
    request.setUrl(QUrl(URL_ANALYSE_SORT));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    QNetworkReply* reply = manager->post(request, postData);

    connect(reply, &QNetworkReply::finished, [=]()
        {

            QJsonDocument replyJson = parseReply(reply);
            //解析返回数据
            QJsonObject obj = replyJson.object();
            QJsonObject tab = obj["table"].toObject();
            // 判断连接是否正常
            if (obj["code"] == "100") {

                while (ui->tableWidget_analyse->rowCount() > 0)
                {
                    ui->tableWidget_analyse->removeRow(ui->tableWidget_analyse->rowCount() - 1);
                }
                on_addrecord_clicked();
                ui->tableWidget_analyse->item(0, 0)->setText("属性");
                QJsonArray field = tab["fields"].toArray();
                // for (int i = 0; i < tab["fieldNum"].toInt(); i++)
                for (int i = 0; i < field.count(); i++)
                {
                    ui->tableWidget_analyse->item(0, i + 1)->setText(field[i].toString());
                }
                QJsonArray det = tab["detail"].toArray();
                //for (int i = 0; i < tab["fieldNum"].toInt(); i++)
                for (int i = 0; i < det.count(); i++)
                {
                    on_addrecord_clicked();
                    int nowrow = ui->tableWidget_analyse->rowCount() - 1;
                    QJsonArray det_1 = det[i].toArray();
                    qDebug() << det_1;
                    for (int j = 0; j < field.count(); j++)
                    {
                        //qDebug() << det_1[j];
                        ui->tableWidget_analyse->item(nowrow, j + 1)->setText(det_1[j].toString());
                    }
                }
            }
            else {
                qDebug() << obj["desc"];
            }});
    qDebug() << "showtable";
}

void UIDemo3::on_addconfirm_clicked() {
    ui->tableWidget_analyse->verticalHeader()->setVisible(false);
    // 构造post数据
    QString tablename = ui->comboBox_gettables->currentText();
    if (tablename == "选择表")
    {
        QMessageBox::warning(this, "警告", "请先选择表");
        return;
    }
    QString user("test");
    QString token("test");
    QString md5("test");
    QString type("add");
    QJsonObject tableObject;
    QJsonObject tableObject_1;
    tableObject.insert("name", tablename);
    tableObject_1.insert("name", tablename);
    QJsonArray detailArray;
    QJsonArray array;
    int nowrow = ui->tableWidget_analyse->rowCount()-1;
    if (nowrow == record_num)
    {
        QMessageBox::warning(this, "警告", "添加失败");
        return;
    }
    int add_num = nowrow - record_num;
    for (int i = add_num; i >0; i--)
    {
        qDebug() << i;
        for (int j = 0; j < field_num; j++)
        {
            array.append(ui->tableWidget_analyse->item(nowrow-i+1, j + 1)->text());
        }
        detailArray.append(array);
        for (int j = 0; j < field_num; j++)
        {
            array.removeFirst();
        }
    }

    tableObject.insert("detail", detailArray);

    QJsonObject json;
    QJsonObject json_1;
    json.insert("user", user);
    json.insert("token", token);
    json.insert("md5", md5);
    json.insert("type", type);
    json.insert("table", tableObject);
    QJsonDocument document;
    document.setObject(json);
    QByteArray dataArray = document.toJson(QJsonDocument::Compact);
    // 发送post数据
    QByteArray postData = document.toJson(QJsonDocument::Compact);
    // 打印post数据
    qDebug() << json;
    qDebug() << json_1;
    // 发送post请求
    QNetworkRequest request;
    request.setUrl(QUrl(URL_ANALYSE_RECORD));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    json_1.insert("user", user);
    json_1.insert("token", token);
    json_1.insert("md5", md5);
    json_1.insert("table", tableObject_1);
    QJsonDocument document_1;
    document_1.setObject(json_1);
    QByteArray dataArray_1 = document_1.toJson(QJsonDocument::Compact);
    // 发送post数据
    QByteArray postData_1 = document_1.toJson(QJsonDocument::Compact);
    // 打印post数据
    QNetworkRequest request_1;
    request_1.setUrl(QUrl(URL_ANALYSE_DETAIL));
    request_1.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    QNetworkReply* reply_1 = manager->post(request_1, postData_1);

    connect(reply_1, &QNetworkReply::finished, [=]()
        {
            QJsonDocument replyJson = parseReply(reply_1);
            //解析返回数据
            QJsonObject obj = replyJson.object();
            QJsonObject tab = obj["table"].toObject();
            // 判断连接是否正常
            if (obj["code"] == "100") {

                while (ui->tableWidget_analyse->rowCount() > 0)
                {
                    ui->tableWidget_analyse->removeRow(ui->tableWidget_analyse->rowCount() - 1);
                }
                on_addrecord_clicked();
                ui->tableWidget_analyse->item(0, 0)->setText("属性");
                QJsonArray field = tab["fields"].toArray();
                // for (int i = 0; i < tab["fieldNum"].toInt(); i++)
                for (int i = 0; i < field.count(); i++)
                {
                    ui->tableWidget_analyse->item(0, i + 1)->setText(field[i].toString());
                }
                QJsonArray det = tab["detail"].toArray();
                record_num = det.count();
                //record_num=tab["recordNum"].toInt();
                //for (int i = 0; i < tab["fieldNum"].toInt(); i++)
                for (int i = 0; i < det.count(); i++)
                {
                    on_addrecord_clicked();
                    int nowrow = ui->tableWidget_analyse->rowCount() - 1;
                    QJsonArray det_1 = det[i].toArray();
                    qDebug() << det_1;
                    for (int j = 0; j < field.count(); j++)
                    {
                        //qDebug() << det_1[j];
                        ui->tableWidget_analyse->item(nowrow, j + 1)->setText(det_1[j].toString());
                    }
                }
            }
            else {
                qDebug() << obj["desc"];
            }

            // 将返回的表各项属性填入editTableWidget中

            // 更新
            ui->tableWidget_analyse->update(); });
    qDebug() << "showtable";
}

void UIDemo3::on_filtrateconfirm_clicked()
{
    ui->tableWidget_analyse->verticalHeader()->setVisible(false);
    if (num == 0)
    {
        QMessageBox::warning(this, "警告", "请输入筛选条件");
    }
    else {

            con = ui->lineEdit_addition->text();
            QString tablename = ui->comboBox_gettables->currentText();
            QString user("test");
            QString token("test");
            QString md5("test");
            QJsonObject tableObject;
            tableObject.insert("name", tablename);

            QJsonObject json;
            json.insert("user", user);
            json.insert("token", token);
            json.insert("md5", md5);
            json.insert("condition", con);
            json.insert("table", tableObject);
            QJsonDocument document;
            document.setObject(json);
            QByteArray dataArray = document.toJson(QJsonDocument::Compact);
            // 发送post数据
            QByteArray postData = document.toJson(QJsonDocument::Compact);
            // 打印post数据
            qDebug() << json;
            // 发送post请求
            QNetworkRequest request;
            request.setUrl(QUrl(URL_ANALYSE_FILTRATE));
            request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
            QNetworkReply* reply = manager->post(request, postData);

            connect(reply, &QNetworkReply::finished, [=]()
                {

                    QJsonDocument replyJson = parseReply(reply);
                    //解析返回数据
                    QJsonObject obj = replyJson.object();
                    QJsonObject tab = obj["table"].toObject();
                    // 判断连接是否正常
                    if (obj["code"] == "100") {

                        while (ui->tableWidget_analyse->rowCount() > 0)
                        {
                            ui->tableWidget_analyse->removeRow(ui->tableWidget_analyse->rowCount() - 1);
                        }
                        on_addrecord_clicked();
                        ui->tableWidget_analyse->item(0, 0)->setText("属性");
                        QJsonArray field = tab["fields"].toArray();
                        // for (int i = 0; i < tab["fieldNum"].toInt(); i++)
                        for (int i = 0; i < field.count(); i++)
                        {
                            ui->tableWidget_analyse->item(0, i + 1)->setText(field[i].toString());
                        }
                        QJsonArray det = tab["detail"].toArray();
                        //for (int i = 0; i < tab["fieldNum"].toInt(); i++)
                        for (int i = 0; i < det.count(); i++)
                        {
                            on_addrecord_clicked();
                            int nowrow = ui->tableWidget_analyse->rowCount() - 1;
                            QJsonArray det_1 = det[i].toArray();
                            qDebug() << det_1;
                            for (int j = 0; j < field.count(); j++)
                            {
                                //qDebug() << det_1[j];
                                ui->tableWidget_analyse->item(nowrow, j + 1)->setText(det_1[j].toString());
                            }
                        }
                    }
                    else {
                        qDebug() << obj["desc"];
                    }});

            ui->stackedWidget_2->setCurrentIndex(0);
            qDebug() << "showtable";
        }
    ui->lineEdit_addition->clear();
    con = "";
    num = 0;


}

void UIDemo3::on_addcondition_clicked()//添加筛选条件
{
    ui->tableWidget_analyse->verticalHeader()->setVisible(false);
    if (num == 0)
    {
        if ((ui->comboBox_attribute->currentText() == NULL || ui->comboBox_symbol->currentText() == NULL || ui->lineEdit_range->text() == NULL)|| ui->lineEdit_addition->text() != NULL) {
            QMessageBox::warning(this, "警告", "请检查条件输入是否有遗漏");
        }
        else {
            con = ui->comboBox_attribute->currentText() + ui->comboBox_symbol->currentText() + ui->lineEdit_range->text();
            ui->lineEdit_addition->setText(con);
            num = 1;
            ui->comboBox_connect->setCurrentIndex(0);
            ui->comboBox_attribute->setCurrentIndex(0);
            ui->comboBox_symbol->setCurrentIndex(0);
            ui->lineEdit_range->clear();
        }

    }
    else {
        if (ui->comboBox_connect->currentText() == NULL || ui->comboBox_attribute->currentText() == NULL || ui->comboBox_symbol->currentText() == NULL || ui->lineEdit_range->text() == NULL) {
            QMessageBox::warning(this, "警告", "请检查条件输入是否有遗漏");
        }
        else {
            con = con + ui->comboBox_connect->currentText() + ui->comboBox_attribute->currentText() + ui->comboBox_symbol->currentText() + ui->lineEdit_range->text();
            ui->lineEdit_addition->setText(con);
            ui->comboBox_connect->setCurrentIndex(0);
            ui->comboBox_attribute->setCurrentIndex(0);
            ui->comboBox_symbol->setCurrentIndex(0);
            ui->lineEdit_range->clear();
        }
    }
    qDebug() << con;


}

void UIDemo3::on_comboBox_connect_currentIndexChanged(int)
{
    if (num == 0)
    {
        if (ui->comboBox_connect->currentText() != NULL)
        {
            QMessageBox::warning(this, "警告", "当前不可选择连接符");
            ui->comboBox_connect->setCurrentIndex(0);
        }
    }
}
//lkl



//xym 三改 新增:删除选定表单
void UIDemo3::on_deleteForm_clicked()
{
    QString user("test");
    QString token("test");
    QString md5("test");

    QJsonArray formArray;

    int temp[100];
    int temp_1=0;
    int now_row = ui->tableWidget_collection->rowCount();
    for (int i = 0; i <now_row; i++)
    {
        if (ui->tableWidget_collection->item(i,0)->checkState() == Qt::Checked) //选中
        {
            temp[i]=1;
            temp_1=1;
        }
    }

    //没有记录被选中点击删除，出警告
    if(temp_1==0)
    {
        QMessageBox::warning(this, "警告", "未选择想要删除的表单！");
    }
    else{
        for(int i=0;i<now_row;i++)
        {
            if(temp[i]==1)
            {
                qDebug() << i;
                QString formId = ui->tableWidget_collection->item(i, 1)->text();

                formArray.append(formId);
            }
        }
    }
    QJsonObject json;
    json.insert("user", user);
    json.insert("token", token);
    json.insert("md5", md5);

    json.insert("formId", formArray);
    QJsonDocument document;
    document.setObject(json);
    //QByteArray dataArray = document.toJson(QJsonDocument::Compact);
    // 发送post数据
    QByteArray postData = document.toJson(QJsonDocument::Compact);
    // 打印post数据
    qDebug() << json;
    // 发送post请求
    QNetworkRequest request;
    request.setUrl(QUrl(URL_COLLECTION_DELETEFORM));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    QNetworkReply* reply = manager->post(request, postData);

    connect(reply, &QNetworkReply::finished, [=]()
    {
        QJsonDocument replyJson = parseReply(reply);
        //解析返回数据
        QJsonObject obj = replyJson.object();
        QJsonObject tab = obj["table"].toObject();
        // 判断连接是否正常
        if (obj["code"] == "100")
        {
            //  逐行清空tablewidget
            while (ui->tableWidget_collection->rowCount() > 0)
            {
                ui->tableWidget_collection->removeRow(ui->tableWidget_collection->rowCount() - 1);
            }

            // 查询所有表单
            QString user("test");
            QString token("test");
            QString md5("test");
            // 构造post数据
            QJsonObject json;
            json.insert("user", user);
            json.insert("token", token);
            json.insert("md5", md5);
            QJsonDocument document;
            document.setObject(json);
            //QByteArray dataArray = document.toJson(QJsonDocument::Compact);
            // 发送post数据
            QByteArray postData = document.toJson(QJsonDocument::Compact);
            // 打印post数据
            qDebug() << json;
            // 发送post请求
            QNetworkRequest request;
            request.setUrl(QUrl(URL_COLLECTION_GETFORMINFO));
            request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
            QNetworkReply* reply = manager->post(request, postData);
            connect(reply, &QNetworkReply::finished, [=]()
            {
                QJsonDocument replyJson = parseReply(reply);
                //解析返回数据
                QJsonObject obj = replyJson.object();

                // 判断连接是否正常
                if (obj["code"] == "100")
                {
                    QJsonArray form = obj["forms"].toArray();
                    qDebug() << form;

                    for (int i = 0; i < form.count(); i++)
                    {
                        //on_addrecord_clicked();
                        int maxrow = ui->tableWidget_collection->rowCount();
                        ui->tableWidget_collection->insertRow(maxrow);
                        ui->tableWidget_collection->setItem(maxrow, 1, new QTableWidgetItem(""));
                        ui->tableWidget_collection->setItem(maxrow, 2, new QTableWidgetItem(""));
                        ui->tableWidget_collection->setItem(maxrow, 3, new QTableWidgetItem(""));

                        int nowrow = ui->tableWidget_collection->rowCount() - 1;
                        QJsonObject det_1 = form[i].toObject();
                        //qDebug() << det_1;
                        ui->tableWidget_collection->item(nowrow, 1)->setText(det_1["id"].toString());
                        ui->tableWidget_collection->item(nowrow, 2)->setText(det_1["name"].toString());
                        ui->tableWidget_collection->item(nowrow, 3)->setText(det_1["url"].toString());
                       // qDebug() << det_1["id"].toString();
                        QTableWidgetItem* item = new QTableWidgetItem();
                        item->setTextAlignment(Qt::AlignCenter);
                        item->setFont(ui->tableWidget_collection->font());
                        item->setCheckState(Qt::Unchecked);
                        ui->tableWidget_collection->setItem(maxrow, 0, item);
                     }
                    //设置表格数据区内的所有单元格都不允许编辑
                    //ui->tableWidget_collection->setEditTriggers(QAbstractItemView::NoEditTriggers);
                }
                else {
                    qDebug() << obj["desc"];
                }
            });
        }
        else {
            qDebug() << obj["desc"];
            QMessageBox::warning(this, "警告", "删除失败！");
        }
    });

    qDebug() << "showtable";
    return;
}

//xym 二次修改 新增:选择表单 显示表单配置和数据
void UIDemo3::on_comboBox_getforms_currentIndexChanged(int index)
{
    ui->tableWidget_formset->setItem(0, 0, new QTableWidgetItem(""));
    ui->tableWidget_formset->setItem(1, 0, new QTableWidgetItem(""));

    //  逐行清空tablewidget
    ui->tableWidget_formset->item(0, 0)->setText("");
    ui->tableWidget_formset->item(1, 0)->setText("");
    while (ui->tableWidget_formset->rowCount() > 4)
    {
        ui->tableWidget_formset->removeRow(ui->tableWidget_formset->rowCount() - 1);
        //ui->tableWidget_formdata->removeRow(ui->tableWidget_formdata->rowCount() - 1);
    }
    while (ui->tableWidget_formdata->columnCount() > 0)
    {
        //ui->tableWidget_formset->removeRow(ui->tableWidget_formset->rowCount() - 1);
        ui->tableWidget_formdata->removeColumn(ui->tableWidget_formdata->columnCount() - 1);
    }

    QString formname = ui->comboBox_getforms->currentText();
    if (formname == "选择表单(点击所选择的表单后请稍等)")
    {
        return;
    }

    // 查询所有表
    QString user("test");
    QString token("test");
    QString md5("test");
    QJsonObject tableObject;
    tableObject.insert("name", formname);
    // 构造post数据
    QJsonObject json;
    json.insert("user", user);
    json.insert("token", token);
    json.insert("md5", md5);
    json.insert("form", tableObject);
    QJsonDocument document;
    document.setObject(json);
    // 发送post数据
    QByteArray postData = document.toJson(QJsonDocument::Compact);
    // 打印post数据
    qDebug() << json;
    // 发送post请求
    QNetworkRequest request;
    request.setUrl(QUrl(URL_COLLECTION_GETFORMDATA));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    QNetworkReply* reply = manager->post(request, postData);
    connect(reply, &QNetworkReply::finished, [=]()
    {
        QJsonDocument replyJson = parseReply(reply);
        //解析返回数据
        QJsonObject obj = replyJson.object();
        QJsonObject form = obj["form"].toObject();
        // 判断连接是否正常
        if (obj["code"] == "100")
        {
            qDebug() << json;
            ui->tableWidget_formset->item(0, 0)->setText(form["id"].toString());
            ui->tableWidget_formset->setSpan(0, 0, 1, 3); //合并单元格
            ui->tableWidget_formset->item(1, 0)->setText(form["name"].toString());
            ui->tableWidget_formset->setSpan(1, 0, 1, 3); //合并单元格
            ui->tableWidget_formset->setSpan(2, 0, 1, 3); //合并单元格
            QJsonArray fields = form["fields"].toArray();
            qDebug() << form["id"].toString();

            for (int i = 0; i < fields.count(); i++)
            {
                //建造显示表单配置的表
                int maxrow = ui->tableWidget_formset->rowCount();
                ui->tableWidget_formset->insertRow(maxrow);
                ui->tableWidget_formset->setItem(maxrow, 0, new QTableWidgetItem(""));
                ui->tableWidget_formset->setItem(maxrow, 1, new QTableWidgetItem(""));
                ui->tableWidget_formset->setItem(maxrow, 2, new QTableWidgetItem(""));

                int nowrow = ui->tableWidget_formset->rowCount() - 1;

                QJsonObject field = fields[i].toObject();
                ui->tableWidget_formset->item(nowrow, 0)->setText(field["name"].toString());
                ui->tableWidget_formset->item(nowrow, 1)->setText(field["table_name"].toString());
                ui->tableWidget_formset->item(nowrow, 2)->setText(field["field_name"].toString());

                //建造显示表单数据的表

                ui->tableWidget_formdata->insertColumn(i);

                ui->tableWidget_formdata->setItem(0, i, new QTableWidgetItem(""));
                ui->tableWidget_formdata->item(0, i)->setText(field["name"].toString());
                QJsonArray dataList = field["data"].toArray();
                qDebug()<<dataList;
                for (int j = 0; j < dataList.count(); j++)
                {
                    ui->tableWidget_formdata->setItem(j+1, i, new QTableWidgetItem(""));
                    ui->tableWidget_formdata->item(j+1, i)->setText(dataList[j].toString());

                }
                //ui->tableWidget_formdata->horizontalHeader()->setVisible(false);
                ui->tableWidget_formdata->verticalHeader()->setVisible(false);
                //ui->tableWidget_formdata->horizontalHeader()->setHidden(true);
            }
            ui->tableWidget_formset->horizontalHeader()->setVisible(false);
            ui->tableWidget_formset->horizontalHeader()->sectionResizeMode(QHeaderView::Stretch);
        }
        else {
            qDebug() << obj["desc"];
        }
    });
    //设置表格数据区内的所有单元格都不允许编辑
    ui->tableWidget_formset->setEditTriggers(QAbstractItemView::NoEditTriggers);
}



